import subprocess
import re
import threading
import time
import os
from Common.handle_path import FIVED_LOGS_DIR

# 全局变量或者标志，控制logcat抓取是否继续
global logcat_running
logcat_running=True
def clear_logcat():
    # 执行adb logcat -c命令来清空日志缓冲区
    subprocess.run(['adb', 'logcat', '-c'])
def run_adb_logcat(stop_event,log_filename):
    adb_command = ['adb', 'logcat']
    process = subprocess.Popen(adb_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    pattern = re.compile(r'ArcAmbient|ZkSeat|ZkConditioner|ZkFragance|ZkShow|5D-SDK|DefaultSeat|DefaultConditioner|DefaultFragance|DefaultShow')

    try:
        with open(log_filename, 'w') as f:
            while logcat_running:
                output_bytes = process.stdout.readline()
                if not output_bytes and process.poll() is not None:
                    break
                if output_bytes:
                    output_str = output_bytes.decode('utf-8', errors='replace').strip()
                    if pattern.search(output_str):
                        # print(output_str)
                        f.write(output_str + '\n')
    except KeyboardInterrupt:
        print("Keyboard Interrupt. Stopping logcat.")
    finally:
        process.kill()
    return process, log_filename

def stop_logcat():
    global logcat_running
    logcat_running = False
    logcat_thread.join()
    logcat_running = True
def start_logcat():
    global logcat_running,logcat_thread
    curTime = time.strftime("%Y-%m-%d %H.%M.%S", time.localtime())
    log_filename = os.path.join(FIVED_LOGS_DIR, "5D_Player_{0}.log".format(curTime))
    logcat_thread = threading.Thread(target=run_adb_logcat, args=(stop_logcat,log_filename))
    logcat_thread.start()
    return logcat_thread, log_filename




if __name__ == "__main__":
    # 启动logcat抓取
    # start_logcat()
    # time.sleep(10)
    #
    # # 这里可以执行其他函数或者代码
    #
    # # 等待其他函数执行完毕，然后停止logcat抓取
    # # logcat_thread.join()
    # stop_logcat()
    # print("Logcat capturing stopped.")
    os.system("adb shell input keyevent 3")
